/*
 * HCSR04_32.c
 *
 * Created: 20-10-2013 00:35:05
 *  Author: Karmu
 */ 


#ifndef F_CPU
#define F_CPU 11059200UL
#endif
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#include "lcd.h"


#define SR_04_TRIGGER	PB3			//PD1 - OUTPUT			
#define SR_04_ECHO		PD6			//PD6 - ICP1

uint16_t getDistance() 
{
	uint16_t t1 = 0, t2 = 0;
	// Simple steps for generating a trigger pulse at trigger pin
	PORTB|=1<<SR_04_TRIGGER;
	_delay_us(15);
	PORTB&=~(1<<SR_04_TRIGGER);
	
	TCCR1A = 0;		
	TCCR1B |= (1<<CS11) | (1<<CS10);	// Timer operating freq is 11.0592MHz/64 (from pre-scalar) gives min. resolution of 5.79us
	
	// ICES1 = 1 for rising edge detection on ICP1
	TCCR1B |= (1<<ICES1);
	
	while((TIFR&(1<<ICF1))==0);	// polled until rising edge detected
	t1 = ICR1;					// Storing the timer value
	
	TIFR = 1<<ICF1;			// Clearing the flag for next use
	
	// ICES1 = 1 for rising edge detection on ICP1
	TCCR1B &=~_BV(ICES1);
	while((TIFR&(1<<ICF1))==0);	// polled until falling edge detected
	t2 = ICR1;					// Storing the timer value
	
	TIFR = 1<<ICF1;			// Clearing the flag for next use
	
	TCCR1B = 0;					//stop timer
	
	return ((t2-t1)*5.79)/58;
}

int main(void)
{
	DDRB|=(1<<SR_04_TRIGGER);
	uint16_t dist = 0;
	sei();
	
	/* initialize LCD display, cursor off */
	lcd_init(LCD_DISP_ON);
	lcd_clrscr();   /* clear display home cursor */
	
	DDRB |= 1<<SR_04_TRIGGER;
    while(1)
    {
		dist=getDistance();
        lcd_putixy(dist,0,0,4); //last parameter is number of digits placeholder
		lcd_putsxy(" cm",4,0);
		_delay_ms(100);
    }
}